/**************************************************
 * Project Name         [JavaEE_XML]
 * File Name            [Dom4jCRUD.java]
 * Creation Date        [08-19-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 **************************************************/
package pkg_03_dom4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * dom4j 节点元素增删改查
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
public class Dom4jCRUD {

	private Document document;

	/**
	 * 获取文档
	 * 
	 * @param documentPath
	 * @return
	 * @throws DocumentException
	 */
	public Document getDocument(String documentPath) throws DocumentException {
		SAXReader xmlReader = new SAXReader();
		document = xmlReader.read(new File(documentPath));
		return document;
	}

	/**
	 * 保存文档(不要使用字节流, 会产生编码问题)
	 * 
	 * @param out
	 * @throws IOException
	 */
	public void writeToXML(OutputStream out) throws IOException {
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		XMLWriter xmlWriter = new XMLWriter(out, format);
		xmlWriter.write(document);
		xmlWriter.flush();
		// 2014-09-08 Add closure code.
		xmlWriter.close();
	}

	/**
	 * 测试方法
	 * 
	 * @param args
	 * @throws DocumentException
	 * @throws IOException
	 */
	public static void main(String[] args) throws DocumentException,
			IOException {
		String documentPath = "src/xml/Student_Dom4j.xml";

		Dom4jCRUD tester = new Dom4jCRUD();
		Document document = tester.getDocument(documentPath);

		// 添加Element, 如果存在多个学生, 则只添加 到第一个
		Element studentElement = document.getRootElement().element("学生");
		Element elementToAdd = studentElement.addElement("hobby");
		elementToAdd.setText("Music");

		// 删除Element, 如果存在多个学生, 则只删除第一个学生中的name
		Element nameElement = studentElement.element("name");
		// studentElement.remove(nameElement);
		nameElement.detach();

		// 修改Element, 如果存在多个学生, 则只修改第一个学生中的age
		Element ageElement = studentElement.element("age");
		ageElement.setName("currentAge");
		ageElement.setText("20");

		FileOutputStream out = new FileOutputStream(documentPath);
		tester.writeToXML(out);

	}
}
